package com.hy.aicodegeneration.langgraph4j.tools;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hy.aicodegeneration.langgraph4j.enums.ImageCategoryEnum;
import com.hy.aicodegeneration.langgraph4j.model.ImageCollectionResult;
import com.hy.aicodegeneration.langgraph4j.model.ImageResource;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 插画图片搜索工具
 */
@Slf4j
@Component
public class UndrawIllustrationTool {

    private static final String UNDRAW_API_URL = "https://undraw.co/_next/data/Qjh7iT41P1b8amtxJWFa_/search/%s.json?term=%s";

    @Tool("搜索插画图片，用于网站美化和装饰")
    public ImageCollectionResult searchIllustrations(@P("搜索关键词") String query) {
        List<ImageResource> imageList = new ArrayList<>();
        int searchCount = 12;
        String apiUrl = String.format(UNDRAW_API_URL, query, query);

        // 使用 try-with-resources 自动释放 HTTP 资源
        try (HttpResponse response = HttpRequest.get(apiUrl).timeout(10000).execute()) {
            if (!response.isOk()) {
                return new ImageCollectionResult(imageList);
            }

            JSONObject result = JSONUtil.parseObj(response.body());
            JSONObject pageProps = result.getJSONObject("pageProps");
            if (pageProps == null) {
                return new ImageCollectionResult(imageList);
            }

            JSONArray illustrations = pageProps.getJSONArray("illustrations");
            if (illustrations == null || illustrations.isEmpty()) {
                return new ImageCollectionResult(imageList);
            }

            // 限制返回数量
            int limit = Math.min(illustrations.size(), searchCount);
            for (int i = 0; i < limit; i++) {
                JSONObject illustration = illustrations.getJSONObject(i);
                String imageId = illustration.getStr("imageId");
                if (StrUtil.isNotBlank(imageId)) {
                    String imageUrl = "https://undraw.co/api/illustrations/" + imageId + "/svg?color=%234f86ed";
                    imageList.add(ImageResource.builder()
                            .category(ImageCategoryEnum.ILLUSTRATION)
                            .description(illustration.getStr("title", query))
                            .url(imageUrl)
                            .build());
                }
            }
        } catch (Exception e) {
            log.error("Undraw API 调用失败: {}", e.getMessage(), e);
        }
        return new ImageCollectionResult(imageList);
    }
}